#!/usr/bin/env python
# -*- coding: utf-8 -*-

# forever mako

import os
dirs = os.path.join( os.path.dirname(__file__),'../..')  #上上级文件目录名
if dirs not in os.sys.path:
    os.sys.path.append(os.path.join( os.path.dirname(__file__), '../..'))   


import urllib2

import SendMessage.Public.Message as Message

class StockNotify:
    def __init__(self,CodeStr=""):
        self.CodeStr=CodeStr
        self.CurrentPrice=None
        self.NotifyPriceLess=None
        self.NotifyPriceMore=None
    
    def IsValid(self):
        return self.NotifyPriceLess or self.NotifyPriceMore
        
    def Check(self):
        if self.CurrentPrice:
            #print(self.CurrentPrice)
            if self.NotifyPriceLess and self.CurrentPrice and float(self.NotifyPriceLess)>=float(self.CurrentPrice):
                Result=Message.NotifyMessage.Send(self.CodeStr,self.CurrentPrice)
                self.NotifyPriceLess=None
                print(Result)
                
            if self.NotifyPriceMore and self.CurrentPrice and float(self.NotifyPriceMore)<=float(self.CurrentPrice):
                Result=Message.NotifyMessage.Send(self.CodeStr,self.CurrentPrice)
                self.NotifyPriceMore=None  
                print(Result)
                
    def UpdateCurrentPrice(self):
        strHtml = urllib2.urlopen('http://hq.sinajs.cn/list='+self.CodeStr).read().split(',')
        if len(strHtml)>3:
            self.CurrentPrice=strHtml[3]
            self.Check()
        else:
            self.NotifyPriceLess=None
            self.NotifyPriceMore=None
            print("Invalid Code:"+self.CodeStr)
            

            
                
class StockPrice:
    def __init__(self):
        self.NotifyList=[]
        self.Load()
        
    def Run(self):
        #print("StockPrice Run")
        self.NotifyList=[N for N in self.NotifyList if N.IsValid()]
        for N in self.NotifyList:
            N.UpdateCurrentPrice()
            N.Check()
        
    def PrintList(self):
        sorted(self.NotifyList,cmp=lambda a,b :cmp(a.CodeStr,b.CodeStr))
        print("All Notify:")
        if len(self.NotifyList)==0:
            print("No Notify")
        else:
            for index in range(len(self.NotifyList)):
                N=self.NotifyList[index]
                print(str(N.CodeStr)+":  L["+str(N.NotifyPriceLess)+"]  M["+str(N.NotifyPriceMore)+"]")
                
    def AddNotify(self,CodeStr,LPrice=None,MPrice=None):
        print(CodeStr,str(LPrice),str(MPrice))
        Notify=None
        for N in self.NotifyList:
            if (not LPrice) and (not MPrice):
                break
            if N.CodeStr==CodeStr:
                if LPrice and (not N.NotifyPriceLess):
                    N.NotifyPriceLess=LPrice
                    LPrice=None
                if MPrice and (not N.NotifyPriceMore):
                    N.NotifyPriceMore=MPrice
                    MPrice=None 
        if LPrice or MPrice:
            Notify=StockNotify(CodeStr)
            Notify.NotifyPriceLess=LPrice
            Notify.NotifyPriceMore=MPrice
            self.NotifyList.append(Notify)
            
    def DeleteNotify(self,index):
        if len(self.NotifyList)>index:
            del self.NotifyList[index]
            
    def ExecCommand(self,Command):
        #Example:
        #StockPrice show
        #StockPrice add L 16.23
        #StockPrice add M 17.52
        #StockPrice del 0
        cmds=Command.split(" ")
        if len(cmds)>=2 and cmds[0]=="StockPrice":
            try:
                if cmds[1]=='show':
                    self.PrintList()
                elif cmds[1]=='add':
                    if cmds[3]=='L':
                        self.AddNotify(cmds[2],cmds[4])
                    elif cmds[3]=='M':
                        self.AddNotify(cmds[2],None,cmds[4])
                elif cmds[1]=='del':
                    self.DeleteNotify(int(cmds[2]))
            except Exception as e:
                print(e)
                
    def Save(self):
        SettingStr=""
        for N in self.NotifyList:
            SettingStr=SettingStr+'\n'+N.CodeStr+' '+str(N.NotifyPriceLess)+" "+str(N.NotifyPriceMore)
        Filename ='%s/StockPriceSetting' % (os.path.split(os.path.realpath(__file__))[0]) 
        SettingFile=open(Filename,'w')
        try:
            SettingFile.writelines(SettingStr)
        except Exception as e:
            print(e)
            SettingFile.close()
            
    
    def Load(self):
        Filename ='%s/StockPriceSetting' % (os.path.split(os.path.realpath(__file__))[0]) 
        SettingFile=open(Filename,'r')
        try:
            for line in SettingFile:
                Settings=line.split(' ')
                if len(Settings)==3:
                    LPrice=Settings[1]
                    if LPrice[:4]=="None":
                        LPrice=None
                    MPrice=Settings[2]
                    if MPrice[:4]=="None":
                        MPrice=None
                    self.AddNotify(Settings[0],LPrice,MPrice)
        except Exception as e:
            print(e)
            SettingFile.close()
            
                
StockPrice=StockPrice()